#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

using namespace std;


const char *pathname = "/home/doujiangge";
const int proj_id = 0xff;
const int defaultsize = 4096;
//基本单位是4kb


key_t GetShmKey()
{
    key_t key = ftok(pathname, proj_id);
    if (key == -1)
    {
        cerr << "GetShmKey Error,errno:" << errno << ",error string:" << strerror(errno) << endl;
        exit(-1);
    }

    return key;
}

int _CreateShm(key_t key, size_t size,int shmflg)
{
    int shmid = shmget(key,size,shmflg);
    if(shmid==-1)
    {
        cerr << "shmget Error,errno:" << errno << ",error string:" << strerror(errno) << endl;
        exit(-1);
    }

    return shmid;
}

int CreateShm(key_t key, size_t size)
{
    //IPC_CREAT|IPC_EXCL存在出错，不存在创建
    return _CreateShm(key,size,IPC_CREAT|IPC_EXCL|0666);
}

int GetShm(key_t key, size_t size)
{
    return _CreateShm(key,size,IPC_CREAT);
}


void DeleteShm(int shmid)
{
    int n = shmctl(shmid,IPC_RMID,nullptr);
    if(n==-1)
    {
        cerr << "DeleteShm Error,errno:" << errno << ",error string:" << strerror(errno) << endl;
        exit(-1);
    }
    else
    {
        cout<<"DeleteShm Success,shmid:"<<shmid<<endl;        
    }

}


void* AttachShm(int shmid)
{
    void* addr = shmat(shmid,nullptr,0);
    if(*(int*)addr==-1)
    {
        cerr << "AttachShm Error,errno:" << errno << ",error string:" << strerror(errno) << endl;
        exit(-1);
    }

    return addr;
}

void DetachShm(void *addr)
{
    int n = shmdt(addr);
    if(n==-1)
    {
        cerr << "DetachShm Error,errno:" << errno << ",error string:" << strerror(errno) << endl;
        exit(-1);
    }
}


string ToHex(int k)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", k);
    return buffer;
}